<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" class="m-r-8" :model="queryParams" :inline="true">
        <el-form-item prop="categoryId">
          <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择分类"
            clearable
            filterable
            class="m-r-8"
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="queryParams.courseKeywords"
            placeholder="请输入课程名称"
            clearable
            class="m-r-8"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button type="success" icon="Plus" @click="handleOpenDialog()">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="currentPageData"
        highlight-current-row
        row-key="id"
        @row-click="handleRowClick"
      >
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="课程名称" align="center">
          <template #default="scope">{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column label="封面" align="center">
          <template #default="scope">
            <img class="cover" :src="scope.row.cover" alt="课程封面" />
          </template>
        </el-table-column>
        <el-table-column label="播放量" align="center" width="120" prop="playCount" />
        <el-table-column label="学习人数" align="center" width="120" prop="studentCount" />
        <el-table-column label="上架时间" align="center" prop="releaseTime" />
        <el-table-column label="难度" align="center" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.difficulty === '高阶' ? 'danger' : 'success'">
              {{ scope.row.difficulty }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时长" align="center" prop="duration" width="160" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.state === 1" type="success">已上架</el-tag>
            <el-tag v-else type="info">已下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="default"
              icon="Edit"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.state === 1 ? 'danger' : 'warning'"
              link
              size="default"
              :icon="scope.row.state === 1 ? 'Bottom' : 'Top'"
              @click.stop="handleStatusChange(scope.row)"
            >
              {{ scope.row.state === 1 ? "下架" : "上架" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination p-8">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="450px" @close="resetForm">
      <el-form ref="menuFormRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入课程名称" />
        </el-form-item>

        <el-form-item label="课程分类" prop="categoryId">
          <el-select
            v-model="formData.categoryId"
            placeholder="请选择课程分类"
            clearable
            filterable
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程难度" prop="difficulty">
          <el-select
            v-model="formData.difficulty"
            placeholder="请选择课程难度"
            clearable
            filterable
          >
            <el-option
              v-for="difficulty in difficultyOptions"
              :key="difficulty"
              :label="difficulty"
              :value="difficulty"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="state">
          <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <!-- 课程封面图片上传 -->
        <el-form-item label="课程封面">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <div class="upload-container">
              <img v-if="formData.cover" :src="formData.cover" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon">
                <el-icon><Plus /></el-icon>
              </i>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程简介" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入课程简介"
          />
        </el-form-item>
        <el-form-item label="课程时长" prop="duration">
          <el-input v-model="formData.duration" placeholder="请输入课程时长（HH:MM:SS）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import http from "@/http/index";
import { beforeImageUpload, uploadImage } from "@/utils/upload";

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0,
});

// 计算当前页数据
const currentPageData = computed(() => {
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  return courseList.value.slice(startIndex, endIndex);
});

// 类型定义（与API返回数据结构一致）
interface CourseItem {
  id: string;
  title: string;
  cover: string;
  playCount: number;
  studentCount: number;
  releaseTime: string;
  duration: string;
  categoryId: string;
  categoryName?: string;
  description: string;
  difficulty: string;
  state: number;
}

interface CategoryItem {
  id: string;
  name: string;
}

interface FormData {
  id?: string;
  title: string;
  description: string;
  cover: string;
  difficulty: string;
  duration: string;
  state: number;
  categoryId: string;
}

// 状态管理
const loading = ref(false);
const dialog = reactive({
  title: "新增实战课程",
  visible: false,
});

// 数据存储
const courseList = ref<CourseItem[]>([]);
const categoryOptions = ref<CategoryItem[]>([]);
const difficultyOptions = ref<string[]>(["中阶", "高阶"]);

// 查询参数
const queryParams = reactive({
  categoryId: "",
  courseKeywords: "",
});

// 表单数据
const initialFormData: FormData = {
  title: "",
  description: "",
  cover: "",
  difficulty: "",
  duration: "",
  state: 1,
  categoryId: "",
};
const formData = ref<FormData>({ ...initialFormData });

// 图片上传相关
const selectedFile = ref<File | null>(null);
const tempPreviewUrl = ref("");
const DURATION_REGEX = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/;

// 表单验证规则
const formRules = reactive({
  title: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择课程分类", trigger: "change" }],
  difficulty: [{ required: true, message: "请选择课程难度", trigger: "change" }],
  duration: [
    { required: true, message: "请输入课程时长", trigger: "blur" },
    {
      pattern: DURATION_REGEX,
      message: "请输入正确的时长格式（HH:MM:SS）",
      trigger: "blur",
    },
  ],
});

// 表单引用
const menuFormRef = ref<FormInstance | null>(null);

// 初始化
onMounted(async () => {
  await fetchCategoryOptions();
  await handleQuery();
});

// 页面卸载时释放临时URL
onUnmounted(() => {
  if (tempPreviewUrl.value) {
    URL.revokeObjectURL(tempPreviewUrl.value);
  }
});

// 获取分类选项
const fetchCategoryOptions = async () => {
  try {
    const result = await http.getCategoryList();
    result.data = result;
    categoryOptions.value = result.data.map((item: any) => ({
      id: item.id,
      name: item.name,
    }));
  } catch (error) {
    console.error("获取分类失败:", error);
    ElMessage.error("获取分类失败，请刷新页面重试");
  }
};

// 分页事件
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  handleQuery();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
};

// 搜索查询
const handleQuery = async () => {
  loading.value = true;
  try {
    const result = await http.getPracticalCourseList(
      queryParams.courseKeywords.trim(),
      queryParams.categoryId
    );

    result.data = result;
    courseList.value = result.data.map((item: any) => ({
      id: item.id,
      title: item.title,
      cover: item.cover,
      playCount: item.playCount || 0,
      studentCount: item.learnerCount || 0,
      releaseTime: item.releaseTime,
      duration: item.duration,
      categoryId: item.categoryProjectID,
      categoryName:
        categoryOptions.value.find((c) => c.id === item.categoryProjectID)?.name || "未分类",
      description: item.description,
      difficulty: item.difficulty,
      state: item.state,
    }));
    pagination.total = courseList.value.length;
    pagination.currentPage = 1;
  } catch (error) {
    console.error("获取课程列表失败:", error);
    ElMessage.error("获取课程失败，请重试");
    courseList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 行点击事件
const handleRowClick = (row: CourseItem) => {
  console.log("点击行数据:", row);
};

// 打开弹窗
const handleOpenDialog = (id?: string) => {
  if (id) {
    const item = courseList.value.find((item) => item.id === id);
    if (item) {
      formData.value = { ...item };
      dialog.title = "编辑实战课程";
    }
  } else {
    resetForm();
    dialog.title = "新增实战课程";
  }
  dialog.visible = true;
};

// 重置表单
const resetForm = () => {
  formData.value = { ...initialFormData };
  selectedFile.value = null;
  if (tempPreviewUrl.value) {
    URL.revokeObjectURL(tempPreviewUrl.value);
    tempPreviewUrl.value = "";
  }
  menuFormRef.value?.resetFields();
};

// 保存课程
const handleSave = async () => {
  if (!menuFormRef.value) return;
  const isValid = await menuFormRef.value.validate();
  if (!isValid) return;

  loading.value = true;
  try {
    let imageUrl = formData.value.cover;
    if (selectedFile.value) {
      imageUrl = await uploadImage(selectedFile.value);
    }

    if (formData.value.id) {
      await http.updatePracticalCourse(
        formData.value.id,
        formData.value.title,
        formData.value.description || "",
        imageUrl,
        formData.value.difficulty,
        formData.value.duration,
        formData.value.state,
        formData.value.categoryId
      );
      ElMessage.success("课程编辑成功");
    } else {
      await http.createPracticalCourse(
        formData.value.title,
        formData.value.description || "",
        imageUrl,
        formData.value.difficulty,
        formData.value.duration,
        formData.value.state,
        formData.value.categoryId
      );
      ElMessage.success("课程新增成功");
    }

    dialog.visible = false;
    await handleQuery();
  } catch (error) {
    console.error("保存课程失败:", error);
    ElMessage.error("保存失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 状态变更
const handleStatusChange = async (row: CourseItem) => {
  const action = row.state === 1 ? "下架" : "上架";
  try {
    await ElMessageBox.confirm(`确定要${action}课程【${row.title}】吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: row.state === 1 ? "warning" : "info",
    });

    await http.changePracticalCourseState(row.id);
    ElMessage.success(`${action}成功`);
    await handleQuery();
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${action}失败:`, error);
      ElMessage.error(`${action}失败，请重试`);
    } else {
      ElMessage.info(`已取消${action}`);
    }
  }
};
// 图片选择变化
const handleFileChange = (file: any) => {
  const rawFile = file.raw;
  if (!rawFile) return;

  if (!beforeImageUpload(rawFile)) {
    selectedFile.value = null;
    return;
  }

  const previewUrl = URL.createObjectURL(rawFile);
  formData.value.cover = previewUrl;
  tempPreviewUrl.value = previewUrl;
  selectedFile.value = rawFile; // 补充赋值操作
};
</script>
<style scoped>
.app-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.input-group {
  display: flex;
  gap: 10px;
}

.cover {
  width: 160px;
  height: 80px;
  object-fit: cover;
  border-radius: 5px;
}

.avatar-uploader {
  display: inline-block;
}

.upload-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 150px;
  height: 100px;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  transition: border-color 0.3s;
}

.upload-container:hover {
  border-color: #409eff;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.pagination {
  float: right;
}
</style>
